package com.dz.lm.common.util;

import java.security.MessageDigest;

public class MD5Util {
	/**
	 * MD5加密。32位
	 * 
	 * @param inStr
	 * @return
	 */
	public static String MD5(String inStr) throws Exception {
		MessageDigest md5 = null;
		StringBuffer hexValue = new StringBuffer();
		try {
			md5 = MessageDigest.getInstance("MD5");
			char[] charArray = inStr.toCharArray();
			byte[] byteArray = new byte[charArray.length];

			for (int i = 0; i < charArray.length; i++)
				byteArray[i] = (byte) charArray[i];

			byte[] md5Bytes = md5.digest(byteArray);

			for (int i = 0; i < md5Bytes.length; i++) {
				int val = ((int) md5Bytes[i]) & 0xff;
				if (val < 16)
					hexValue.append("0");
				hexValue.append(Integer.toHexString(val));
			}
		} catch (Exception e) {
			throw new Exception("MD5加密失败！");
		}
		return hexValue.toString();
	}

	/**
	 * MD5加密。32位
	 * 
	 * @param inStr
	 * @return
	 */
	public static String MD5(Object objStr) throws Exception {
		MessageDigest md5 = null;
		StringBuffer hexValue = new StringBuffer();
		String inStr = "";
		try {
			if (objStr == null || "".equals(objStr.toString())) {
				throw new Exception("字符串为空，MD5加密失败！");
			} else {
				inStr = objStr.toString();
			}
			md5 = MessageDigest.getInstance("MD5");
			char[] charArray = inStr.toCharArray();
			byte[] byteArray = new byte[charArray.length];

			for (int i = 0; i < charArray.length; i++)
				byteArray[i] = (byte) charArray[i];

			byte[] md5Bytes = md5.digest(byteArray);

			for (int i = 0; i < md5Bytes.length; i++) {
				int val = ((int) md5Bytes[i]) & 0xff;
				if (val < 16)
					hexValue.append("0");
				hexValue.append(Integer.toHexString(val));
			}
		} catch (Exception e) {
			throw new Exception("MD5加密失败！");
		}
		return hexValue.toString();
	}

}
